package com.tusuo.stds.ui.login;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andreabaccega.widget.FormEditText;
import com.tusuo.stds.Constants;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.util.validator.MobilePhoneNumberValidator;
import com.tusuo.stds.util.validator.PasswordValidator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import myandroid.library.util.ApplicationHelper;
import rx.functions.Action0;

@EActivity(R.layout.activity_login)
public class LoginActivity extends BaseToolbarActivity<LoginView, LoginPresenter>
                                implements LoginView {

    @ViewById(R.id.login_layout_wechat)
    LinearLayout layoutWechat;
    @ViewById(R.id.tv_msg)
    TextView tvMsg;
    @ViewById(R.id.et_mobile_num)
    FormEditText etMobileNum;
    @ViewById(R.id.et_password)
    FormEditText etPassword;
    @ViewById(R.id.login_btn_login)
    Button btnLogin;

    @StringRes(R.string.toolbar_title_login)
    String toolbarTitle;
    @StringRes(R.string.toolbar_menu_register)
    String toolbarMenuRegister;
    @StringRes(R.string.err_msg_mobile_number)
    String strErrMsgMobileNumber;
    @StringRes(R.string.err_msg_password)
    String strErrMsgPassword;
    @StringRes(R.string.login_3rd_login_tip)
    String strThirdLoginTip;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    @AfterViews
    void afterViews() {
        setupUI(this, toolbarBgColor, toolbarTextColor);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction(toolbarMenuRegister, new Action0() {
            @Override
            public void call() {
                presenter.register();
            }
        }, 0);

        menuActionList.add(menuAction);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, false, 0, menuActionList);
        mToolbarOwner.setConfig(config);

        btnLogin.setEnabled(false);

        etMobileNum.addTextChangedListener(new EditTextChangedListener());
        etPassword.addTextChangedListener(new EditTextChangedListener());

        etMobileNum.addValidator(new MobilePhoneNumberValidator(strErrMsgMobileNumber));
        etPassword.addValidator(new PasswordValidator(strErrMsgPassword));

        if (!Utils.App.isWXAppInstalled(this)) {
            layoutWechat.setVisibility(View.GONE);
        }

        ApplicationHelper.getInstance().addActivity(this);
    }


    @NonNull
    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter(this);
    }

    @Override
    protected void onDestroy() {
//        ShareSDK.stopSDK(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (presenter.checkDoubleClick()) {
            ApplicationHelper.getInstance().exit();
            super.onBackPressed();
        }
    }

    @Override
    public void showErrMsg(String text) {
        tvMsg.setText(text);
        tvMsg.setTextColor(Color.RED);
    }

    @Override
    public void showSlogan() {
        tvMsg.setText(getString(R.string.slogan));
        tvMsg.setTextColor(Color.WHITE);
    }


    @Click(R.id.login_btn_reset_password)
    void clickResettingPasswordBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        presenter.resetPassword();
    }

    @Click(R.id.login_btn_login)
    void clickLoginBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        // 强制隐藏软键盘
        Utils.UI.closeInputMethod(this);

        if (!etMobileNum.testValidity()) {
            presenter.showErrMsg(strErrMsgMobileNumber);
            return;
        }

        if (!etPassword.testValidity()) {
            presenter.showErrMsg(strErrMsgPassword);
            return;
        }

        presenter.login(etMobileNum.getText().toString(),
                etPassword.getText().toString());
    }

    @Click({R.id.login_layout_qq, R.id.login_btn_qq, R.id.login_tv_qq})
    void loginAsQqAccount() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Utils.UI.showToastLong(strThirdLoginTip);

//        ShareSDK.initSDK(this);

        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        qq.removeAccount(true);
        authorize(qq);
    }

    @Click({R.id.login_layout_wechat, R.id.login_btn_wechat, R.id.login_tv_wechat})
    void loginAsWeChatAccount() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Utils.UI.showToastLong(strThirdLoginTip);
//        ShareSDK.initSDK(this);

        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
        weChat.removeAccount(true);
        authorize(weChat);
    }

    @Click({R.id.login_layout_sina, R.id.login_btn_sina, R.id.login_tv_sina})
    void loginAsSinaWeiboAccount() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Utils.UI.showToastLong(strThirdLoginTip);
//        ShareSDK.initSDK(this);

        Platform sinaWeibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        sinaWeibo.removeAccount(true);
        authorize(sinaWeibo);
    }

    //执行授权,获取用户信息
    //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(final Platform plat) {
        if (plat == null) {
            return;
        }

        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> res) {

                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    ThirdLoginUserInfo info = new ThirdLoginUserInfo();
                    info.openId = platDB.getUserId();
                    switch (plat.getName()) {
                        case "Wechat":
                            info.platForm = Constants.PLATFORM.WECHAT;
                            break;
                        case "QQ":
                            info.platForm = Constants.PLATFORM.QQ;
                            break;
                        case "SinaWeibo":
                            info.platForm = Constants.PLATFORM.WEIBO;
                            break;
                        default:
                            return;
                    }
                    info.userIcon = platDB.getUserIcon();
                    info.accessToken = platDB.getToken();
                    info.nickName = platDB.getUserName();
                    // 别放Toast! ShareSDK会报错！
                    presenter.thirdLogin(info);
                } else {
                }
            }

            @Override
            public void onError(Platform platform, int action, Throwable throwable) {
                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    ThirdLoginUserInfo info = new ThirdLoginUserInfo();
                    info.openId = platDB.getUserId();
                    switch (plat.getName()) {
                        case "Wechat":
                            info.platForm = Constants.PLATFORM.WECHAT;
                            break;
                        case "QQ":
                            info.platForm = Constants.PLATFORM.QQ;
                            break;
                        case "SinaWeibo":
                            info.platForm = Constants.PLATFORM.WEIBO;
                            break;
                        default:
//                            Utils.UI.showToastLong("第三方登录操作失败");
                            return;
                    }
                    info.userIcon = platDB.getUserIcon();
                    info.accessToken = platDB.getToken();
                    info.nickName = platDB.getUserName();
                    // 别放Toast! ShareSDK会报错！
                    presenter.thirdLogin(info);
                } else {
                    Utils.UI.showToastShort("第三方登录操作失败");
                }
            }

            @Override
            public void onCancel(Platform platform, int action) {
                Utils.UI.showToastShort("第三方登录操作取消");
            }
        });

        // 登录的时候走客户端,如果没有客户端会调转到网页版
        plat.SSOSetting(false);
        plat.showUser(null);//执行登录，登录后在回调里面获取用户资料
    }

    private class EditTextChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etMobileNum.getText().length() > 0 && etPassword.getText().length() > 0) {
                btnLogin.setBackgroundResource(R.drawable.selector_theme_button);
                btnLogin.setEnabled(true);
            } else {
                btnLogin.setBackgroundResource(R.drawable.shape_theme_button_disabled);
                btnLogin.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}
